package com.bigData.main.TestSocket;

import com.bigData.main.TestHDFS.TestConnectionHDFS;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URISyntaxException;

public class TestClient {
    public static void main(String[] args) throws IOException, URISyntaxException {
        //创建客户端对象，指定端口和ip
        Socket c = new Socket("127.0.0.1", 8099);
        TestConnectionHDFS t = new TestConnectionHDFS();
        t.init();
//        t.upload("D:\\gongfang\\car.txt","/myfile_cax/car.txt");
        //获取客户端输出流
        OutputStream out = c.getOutputStream();
        //获取客户端输入流
        InputStream in = c.getInputStream();

        String str = "getCarMessage";
        //发送数据
        out.write(str.getBytes());
        //将流置于流末尾
        c.shutdownOutput();

        //读取服务端信息
        byte[] b = new byte[1024];
        //保存读取到的字节个数
        int num = 0;
        //保存最终的信息
        String xmlPress1 = "";
        while ((num = in.read(b)) != -1) {
            //将字节数组转为字符串
            String str1 = new String(b, 0, num);
            xmlPress1 += str1;
        }
        //判断服务端返回值
        if (xmlPress1.equals("erro")) {
            System.out.println("请求协议错误");
        } else {
            new Method().passXML(xmlPress1);
        }

        //解析
//        new method().passXML(xmlPress1);
    }

//关流
//        out.close();


// TestClient.java

    public static String verifyCode(String code, String ip) throws IOException {
        try (Socket socket = new Socket(ip, 8099)) { // 使用动态IP
            OutputStream out = socket.getOutputStream();
            out.write((code + "\n").getBytes());

            InputStream in = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString().trim();
        }
    }

    public static boolean pingServer(String ip) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(ip, 8099), 3000);
            return true;
        } catch (IOException e) {
            return false;
        }
    }


}
